package com.poetize.plus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetize.plus.entity.po.ArticleDislike;
import com.poetize.plus.entity.po.ArticleLike;
import com.poetize.plus.mapper.ArticleDislikeMapper;
import com.poetize.plus.mapper.ArticleLikeMapper;
import com.poetize.plus.service.ArticleDislikeService;
import com.poetize.plus.utils.LoginUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author zuosy
 * @created 2024/4/11 10:22
 */
@Service
@RequiredArgsConstructor
public class ArticleDislikeServiceImpl extends ServiceImpl<ArticleDislikeMapper, ArticleDislike> implements ArticleDislikeService {

    private final ArticleLikeMapper articleLikeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean dislikeArticle(Long articleId) {
        var userName = LoginUtils.getLoginUserName();

        var dislike = lambdaQuery()
                .eq(ArticleDislike::getArticleId, articleId)
                .eq(ArticleDislike::getCreateBy, userName)
                .one();

        /*
         * 1：如果还没点踩就增加点踩，如果同时存在对该文章的点赞操作，则会取消点赞；
         * 2：如果已经点踩，则取消点踩；
         * */
        return Optional.ofNullable(dislike)
                .map(d -> baseMapper.deleteById(d) > 0)
                .orElseGet(() -> {
                    var articleDislike = new ArticleDislike();
                    articleDislike.setArticleId(articleId);
                    baseMapper.insert(articleDislike);

                    articleLikeMapper.delete(new LambdaQueryWrapper<ArticleLike>()
                            .eq(ArticleLike::getArticleId, articleId)
                            .eq(ArticleLike::getCreateBy, userName));
                    return true;
                });
    }
}
